package a02_链表;

/**
 * <p>
 * a02_设计链表
 * </p>
 *
 * @author flyduck
 * @since 2024-06-14
 */
public class a03_设计链表复习4 {

    public static void main(String[] args) {
        a03_设计链表复习4 myLinkedList = new a03_设计链表复习4();
//        myLinkedList.addAtHead(1);
//        myLinkedList.addAtTail(3);
//        myLinkedList.addAtIndex(1, 2);    // 链表变为 1->2->3
//        myLinkedList.get(1);              // 返回 2
//        myLinkedList.deleteAtIndex(1);    // 现在，链表变为 1->3
//        myLinkedList.get(1);
//        myLinkedList.addAtTail(1);
//        myLinkedList.get(0);
        myLinkedList.addAtTail(1);

    }

//    private static void print(a03_设计链表 myLinkedList) {
//        ListNode dummy=myLinkedList.dummy;
//        ListNode temp = dummy.next;
//        while (temp != null){
//            System.out.println(temp.val);
//            temp = temp.next;
//        }
//    }

    private ListNode dummyNode;
    private int size;


    public a03_设计链表复习4() {
        this.dummyNode = new ListNode(0);
        this.size = 0;
    }

    public int get(int index) {
        if(index < 0 || index >= this.size){
            return -1;
        }

        ListNode currentNode = dummyNode.next;
        while (index > 0) {//假设index = 0，此处不会进来
            currentNode = currentNode.next;
            index--;
        }
        return currentNode.val;
    }

    public void addAtHead(int val) {
        ListNode newNode = new ListNode(val);
        newNode.next = dummyNode.next;
        dummyNode.next = newNode;
        size++;
    }

    public void addAtTail(int val) {
        ListNode currentNode = dummyNode;
        while (currentNode.next != null) {
            currentNode = currentNode.next;
        }
        ListNode newNode = new ListNode(val);
        currentNode.next = newNode;
        size++;
    }

    public void addAtIndex(int index, int val) {
        if(index < 0 || index > this.size){
            return;
        }

        ListNode currentNode = dummyNode;
        while (index > 0){
            currentNode = currentNode.next;
            index--;
        }

        ListNode newNode = new ListNode(val);
        newNode.next = currentNode.next;
        currentNode.next = newNode;
        size++;
    }

    public void deleteAtIndex(int index) {
        if(index < 0 || index >= this.size){
            return;
        }
        ListNode currentNode = dummyNode;
        while (index > 0){
            currentNode = currentNode.next;
            index--;
        }
        currentNode.next = currentNode.next.next;
        size--;
    }
}
